package com.yiwei.zxp.fragment;

import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.zxp.R;
import com.yiwei.zxp.activity.BoothPacketActivity;
import com.yiwei.zxp.activity.GoodsAddActivity;
import com.yiwei.zxp.activity.SettingShopActivity;
import com.yiwei.zxp.adapter.PacketLeftAdapter;
import com.yiwei.zxp.adapter.PacketRightAdapter;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.BoothGoodListBean;
import com.yiwei.zxp.constant.UserInfoGlobal;
import com.yiwei.zxp.event.MainPacketEvent;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.NoticeView;
import com.yiwei.zxp.view.OnLoadeMoreListener;
import com.yiwei.zxp.view.ShopIdentitySuccessDilaog;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 18-5-22.
 */

public class MainPacketFragment extends BaseFragment {
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_notice)
    NoticeView txtNotice;
    @BindView(R.id.list_left)
    RecyclerView listLeft;
    @BindView(R.id.list_right)
    RecyclerView listRight;
    @BindView(R.id.layout_has_buy)
    LinearLayout layoutHasBuy;
    @BindView(R.id.btn_buy_packet)
    SuperButton btnBuyPacket;
    @BindView(R.id.layout_business_empty)
    LinearLayout layoutBusinessEmpty;

    @BindView(R.id.refresh)
    SwipeRefreshLayout refresh;
    @BindView(R.id.btn_shop_name)
    TextView btnShopName;
    @BindView(R.id.btn_add_goods)
    SuperButton btnAddGoods;
    @BindView(R.id.layout_empty)
    LinearLayout layoutEmpty;
    @BindView(R.id.tablayout)
    TabLayout tablayout;
    Unbinder unbinder;
    @BindView(R.id.img_status)
    ImageView imgStatus;
    @BindView(R.id.txt_tips)
    TextView txtTips;
    @BindView(R.id.btn_upload)
    SuperButton btnUpload;
    @BindView(R.id.layout_identity_status)
    LinearLayout layoutIdentityStatus;
    @BindView(R.id.btn_add_empty)
    SuperButton btnAddEmpty;
    private PacketLeftAdapter packetLeftAdapter;
    private PacketRightAdapter packetRightAdapter;
    private int selectStatus = 1;
    private String select_cate_id;
    private static final int Status_Sell = 1;
    private static final int Status_Ing = 0;
    private static final int Status_Down = 2;

    //    private ShopNameDilaog shopNameDilaog;
    private boolean is_identity = false;
    private boolean is_need_change_tab = false;
    private OnLoadeMoreListener loadeMoreListener = new OnLoadeMoreListener() {
        @Override
        public void onLoadMore(int page) {
            loadeMoreListener.setPage(1);
            getGoodsList(page, select_cate_id, selectStatus);
        }
    };

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_my_packet;
    }

    @Override
    protected void initView() {
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    selectStatus = Status_Sell;
                } else if (tab.getPosition() == 1) {
                    selectStatus = Status_Ing;
                } else if (tab.getPosition() == 2) {
                    selectStatus = Status_Down;
                }
                loadeMoreListener.setPage(1);
                getGoodsList(1, select_cate_id, selectStatus);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!UserInfoGlobal.isLogin()) {
                    refresh.setRefreshing(false);
                    return;
                }
                getShopAuthCheck();

            }
        });
        packetLeftAdapter = new PacketLeftAdapter(getContext());
        packetLeftAdapter.setOnChooseListener(new PacketLeftAdapter.OnChooseListener() {
            @Override
            public void onClick(String cate_id) {
                select_cate_id = cate_id;
                if (!is_need_change_tab) {
                    selectStatus = Status_Sell;
                    tablayout.getTabAt(0).select();
                    is_need_change_tab = false;
                }

                loadeMoreListener.setPage(1);
                getGoodsList(1, cate_id, selectStatus);
            }
        });
        listLeft.setAdapter(packetLeftAdapter);
        packetRightAdapter = new PacketRightAdapter(getContext());
        listRight.setAdapter(packetRightAdapter);
        listRight.addOnScrollListener(loadeMoreListener);
        EventBus.getDefault().register(this);
    }

    private boolean is_need_load = false;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MainPacketEvent event) {
        is_need_load = true;
        if (!TextUtils.isEmpty(event.poi)) {
            is_need_change_tab = true;
            switch (event.poi) {
                case "0":
                    selectStatus = Status_Sell;
                    tablayout.getTabAt(Integer.valueOf(event.poi)).select();
                    break;
                case "1":
                    selectStatus = Status_Ing;
                    tablayout.getTabAt(Integer.valueOf(event.poi)).select();
                    break;
                case "2":
                    selectStatus = Status_Down;
                    tablayout.getTabAt(Integer.valueOf(event.poi)).select();
                    break;
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (is_need_load) {
            getShopAuthCheck();
            packetLeftAdapter.setSelectPoi();
        }else {
            if (UserInfoGlobal.isLogin()) {
                getShopAuthCheck();
//            btnShopName.setVisibility(View.VISIBLE);
                if(txtRight!=null)
                    txtRight.setVisibility(View.VISIBLE);
            } else {
                try {
                    layoutHasBuy.setVisibility(View.GONE);
                    layoutBusinessEmpty.setVisibility(View.VISIBLE);
                    txtRight.setVisibility(View.GONE);
                    btnShopName.setVisibility(View.GONE);
                }catch (NullPointerException e){

                }

            }
        }
        is_need_load = false;
    }



    public void getBoothNum() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);
        Api.api_service.getBoothNum().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    refresh.setRefreshing(false);
                    if (result.datas.booths > 0) {
//                        已认证店铺
                        if (is_identity) {
                            btnShopName.setVisibility(View.VISIBLE);
                            layoutHasBuy.setVisibility(View.VISIBLE);
                            layoutBusinessEmpty.setVisibility(View.GONE);
                            List<String> list = new ArrayList<String>();
                            list.add("您总共有" + result.datas.booths + "个展位，空闲展位" + result.datas.last_booths + "个");
                            txtNotice.setList(list);
                            if (result.datas.booths == result.datas.last_booths) {
                                tablayout.setVisibility(View.GONE);
                                listLeft.setVisibility(View.GONE);
                                btnAddEmpty.setVisibility(View.VISIBLE);
                            } else {
                                tablayout.setVisibility(View.VISIBLE);
                                listLeft.setVisibility(View.VISIBLE);
                                btnAddEmpty.setVisibility(View.GONE);
                            }
                        } else {
//                            未认证店铺
                            layoutBusinessEmpty.setVisibility(View.GONE);
                            layoutIdentityStatus.setVisibility(View.VISIBLE);
                        }
                        txtRight.setVisibility(View.VISIBLE);
                    } else {
                        btnShopName.setVisibility(View.GONE);
                        layoutHasBuy.setVisibility(View.GONE);
                        layoutBusinessEmpty.setVisibility(View.VISIBLE);
                        txtRight.setVisibility(View.GONE);


                    }

                });
    }

    //    店铺审核情况
    public void getShopAuthCheck() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }
        if (refresh != null) {
            refresh.setRefreshing(true);
        }


        Api.api_service.getShopAuthCheck().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    refresh.setRefreshing(false);
                    UserInfoGlobal.setIsHasShopName(result.datas.type);
                    String type = result.datas.type;
                    switch (type) {
                        case "-2":
                            is_identity = false;
                            layoutHasBuy.setVisibility(View.GONE);
                            btnShopName.setText("请设置店铺名");
                            btnShopName.setVisibility(View.VISIBLE);
                            layoutIdentityStatus.setVisibility(View.GONE);
                            btnUpload.setVisibility(View.VISIBLE);
                            btnUpload.setText("立即认证");
                            txtTips.setText("亲，您的店铺还没有进行认证喔\n只有通过了认证，才能添加商品啦");
                            imgStatus.setImageResource(R.mipmap.img_shop_need_identity);
                            getCateList();
                            getBoothNum();
                            break;
                        case "-1":
                            is_identity = false;
                            layoutBusinessEmpty.setVisibility(View.GONE);
                            layoutHasBuy.setVisibility(View.GONE);
                            layoutIdentityStatus.setVisibility(View.VISIBLE);
                            imgStatus.setImageResource(R.mipmap.img_packet_fail);
//                            txtTips.setText("很抱歉，您的店铺资料未通过审核\n未通过原因是资质认证照片不清晰");
                            txtTips.setText(result.msg);
                            btnUpload.setVisibility(View.VISIBLE);
                            btnUpload.setText("重新上传");
                            btnShopName.setVisibility(View.VISIBLE);
                            btnShopName.setText("资料审核失败");
                            txtRight.setVisibility(View.VISIBLE);
                            break;
                        case "0":
                            is_identity = false;
                            layoutBusinessEmpty.setVisibility(View.GONE);
                            layoutHasBuy.setVisibility(View.GONE);
                            layoutIdentityStatus.setVisibility(View.VISIBLE);
                            btnUpload.setVisibility(View.GONE);
                            imgStatus.setImageResource(R.mipmap.img_packet_ing);
                            Spanned txtTip = Spans.with(this).font("店铺资料已提交后台审核，请耐心等待\n", getResources().getDimensionPixelSize(R.dimen.x30), 0xff000000).
                                    font("您提交的信息会在1个工作日内审核完毕\n请注意关注通知", getResources().getDimensionPixelSize(R.dimen.x24), 0xff999999).
                                    build();
                            txtTips.setText(txtTip);
                            btnShopName.setVisibility(View.VISIBLE);
                            btnShopName.setText("资料审核中");
                            txtRight.setVisibility(View.VISIBLE);
                            break;
                        case "1":
                            is_identity = true;
                            layoutIdentityStatus.setVisibility(View.GONE);
                            if (UserInfoGlobal.isDialogOnce()) {
                                new ShopIdentitySuccessDilaog(getContext()).setOnChooseListener(new ShopIdentitySuccessDilaog.OnChooseListener() {
                                    @Override
                                    public void onSuccess(String shop_name) {
                                        Util.startActivity(getContext(), GoodsAddActivity.class);
                                    }

                                    @Override
                                    public void onLock() {
                                        getCateList();
                                        getBoothNum();
                                    }
                                }).show();
                                UserInfoGlobal.setDialogOnce(false);
                            } else {
                                getCateList();
                                getBoothNum();
                            }
                            btnShopName.setVisibility(View.VISIBLE);
                            btnShopName.setText(result.datas.info.shop_name);
                            txtRight.setVisibility(View.VISIBLE);
//                            imgStatus.setImageResource(R.mipmap.img_packet_success);
                            break;
                    }
                });
    }


    public void getCateList() {
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        Api.api_service.getCateList().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    packetLeftAdapter.update(result.datas);
                    if (packetLeftAdapter.getItemCount() != 0) {
                        listLeft.setVisibility(View.VISIBLE);
                        if (TextUtils.isEmpty(select_cate_id)) {
                            select_cate_id = result.datas.get(0).cate_id;
                        }
                        getGoodsList(1, select_cate_id, selectStatus);
                    } else {

                    }
                });
    }

    public void getGoodsList(int page, String cate_id, int status) {
        if (TextUtils.isEmpty(select_cate_id)) {
            return;
        }
        if (!Network.checkNetwork(getContext())) {
            ToastUtil.show(getContext(), "网络连接失败");
            return;
        }

        refresh.setRefreshing(true);
        BoothGoodListBean bean = new BoothGoodListBean();
        bean.page = page;
        bean.cate_id = cate_id;
        bean.status = status + "";
        Api.api_service.getBoothGoodList(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    refresh.setRefreshing(false);
                    packetRightAdapter.add(result.datas, page == 1);
                    if (packetRightAdapter.getItemCount() == 0) {
                        layoutEmpty.setVisibility(View.VISIBLE);
                    } else {
                        layoutEmpty.setVisibility(View.GONE);
                    }
                });
    }


    @OnClick({R.id.btn_add_empty, R.id.btn_upload, R.id.btn_add_goods, R.id.txt_right, R.id.btn_buy_packet, R.id.btn_shop_name})
    public void onViewClicked(View view) {
        if (UI.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_add_goods:
                if (UserInfoGlobal.isHasShopName()) {
                    Util.startActivity(getActivity(), GoodsAddActivity.class);
                } else {
                    Dialog.showDefaultDialog(getContext(), "", "请先设置店铺名，才能添加商品喔", "", "好，立即设置", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            Util.startActivity(getActivity(), SettingShopActivity.class);
//                            shopNameDilaog.show();
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                }
//                ToastUtil.makeText(getContext(), "功能开发中");
                break;
            case R.id.btn_add_empty:
                Util.startActivity(getActivity(), GoodsAddActivity.class);
                break;
            case R.id.btn_upload:
                Util.startActivity(getActivity(), SettingShopActivity.class);
                break;
            case R.id.txt_right:
                Util.startActivity(getActivity(), BoothPacketActivity.class);
                break;
            case R.id.btn_buy_packet:
                Util.startActivity(getActivity(), BoothPacketActivity.class);
                break;
            case R.id.btn_shop_name:
                if (UI.toString(btnShopName).equals("请设置店铺名")) {
                    Util.startActivity(getActivity(), SettingShopActivity.class);
                } else {
                    if (UI.toString(btnShopName).equals("资料审核中") || UI.toString(btnShopName).equals("资料审核失败")) {
                        return;
                    }
                    Dialog.showDefaultDialog(getContext(), "", "您已设置店铺名，无需再次设置", "", "好，我知道了", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {

                        }

                        @Override
                        public void cancel() {

                        }
                    });
                    return;
                }
                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
//        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }
}
